<template>
  <div class="profile-page">
    <!-- 用户信息头部 -->
    <div class="user-header">
      <div class="header-background"></div>
      <div class="user-info-card">
        <div class="avatar-section">
          <el-avatar
              :size="80"
              :src="userInfo.avatar"
              class="user-avatar"
              @click="handleAvatarClick"
          >
            <span v-if="!userInfo.avatar" class="avatar-fallback">
              {{ userInfo.username?.charAt(0) || '用户' }}
            </span>
          </el-avatar>
          <div class="verify-badge" v-if="userInfo.verified">
            <el-icon color="#00a1d6"><Select /></el-icon>
          </div>
        </div>

        <div class="user-basic-info">
          <div class="username-section">
            <h2 class="username">{{ userInfo.username }}</h2>
            <el-tag v-if="userInfo.vipLevel" type="warning" class="vip-tag">
              LV{{ userInfo.vipLevel }}
            </el-tag>
          </div>
          <p class="user-signature">{{ userInfo.description || '这个人很懒，什么都没有写～' }}</p>
          <div class="user-meta">
            <span class="meta-item">
              <el-icon><Location /></el-icon>
              {{ userInfo.location || '未知地区' }}
            </span>
            <span class="meta-item">
              <el-icon><Calendar /></el-icon>
              加入于 {{ formatJoinDate(userInfo.joinDate) }}
            </span>
          </div>
        </div>

        <div class="user-actions">
          <el-button type="primary" icon="EditPen" @click="handleEditProfile">
            编辑资料
          </el-button>
          <el-button icon="Share" @click="handleShareProfile">
            分享
          </el-button>
        </div>
      </div>
    </div>

    <!-- 主要内容区 -->
    <div class="main-content">
      <!-- 个人数据统计 -->
      <el-row :gutter="20" class="stats-section">
        <el-col :span="8">
          <div class="user-stats-card">
            <h3 class="stats-title">个人数据</h3>
            <div class="stats-grid">
              <div class="stat-item" @click="navigateTo('dynamic')">
                <div class="stat-value">{{ formatCount(userStats.dynamic) }}</div>
                <div class="stat-label">动态</div>
                <el-icon class="stat-icon"><ChatDotRound /></el-icon>
              </div>
              <div class="stat-item" @click="navigateTo('following')">
                <div class="stat-value">{{ formatCount(userStats.following) }}</div>
                <div class="stat-label">关注</div>
                <el-icon class="stat-icon"><User /></el-icon>
              </div>
              <div class="stat-item" @click="navigateTo('followers')">
                <div class="stat-value">{{ formatCount(userStats.followers) }}</div>
                <div class="stat-label">粉丝</div>
                <el-icon class="stat-icon"><Star /></el-icon>
              </div>
            </div>

            <!-- 扩展统计 -->
            <div class="extended-stats">
              <div class="extended-stat">
                <span class="extended-label">获赞数</span>
                <span class="extended-value">{{ formatCount(userStats.likes) }}</span>
              </div>
              <div class="extended-stat">
                <span class="extended-label">播放数</span>
                <span class="extended-value">{{ formatCount(userStats.views) }}</span>
              </div>
              <div class="extended-stat">
                <span class="extended-label">收藏数</span>
                <span class="extended-value">{{ formatCount(userStats.favorites) }}</span>
              </div>
            </div>
          </div>
        </el-col>

        <!-- 最近动态 -->
        <el-col :span="16">
          <div class="recent-activity">
            <div class="activity-header">
              <h3>最近动态</h3>
              <el-button type="text" @click="refreshActivities">
                <el-icon><Refresh /></el-icon>
                刷新
              </el-button>
            </div>

            <div v-if="loading" class="loading-activities">
              <el-icon class="loading-icon"><Loading /></el-icon>
              <span>加载中...</span>
            </div>

            <div v-else-if="activities.length === 0" class="empty-activities">
              <el-empty description="暂无动态">
                <span>还没有任何动态记录</span>
              </el-empty>
            </div>

            <el-timeline v-else>
              <el-timeline-item
                  v-for="activity in activities"
                  :key="activity.id"
                  :timestamp="formatActivityTime(activity.time)"
                  :type="getActivityType(activity.type)"
                  placement="top"
                  class="activity-item"
              >
                <el-card class="activity-card" shadow="hover">
                  <div class="activity-content">
                    <div class="activity-icon">
                      <el-icon v-if="activity.type === 'like'"><Star /></el-icon>
                      <el-icon v-if="activity.type === 'comment'"><ChatDotRound /></el-icon>
                      <el-icon v-if="activity.type === 'post'"><EditPen /></el-icon>
                      <el-icon v-if="activity.type === 'share'"><Share /></el-icon>
                    </div>
                    <div class="activity-details">
                      <p class="activity-text">{{ activity.content }}</p>
                      <div v-if="activity.target" class="activity-target">
                        《{{ activity.target }}》
                      </div>
                    </div>
                  </div>
                  <div class="activity-actions">
                    <el-button type="text" size="small" @click="viewActivity(activity)">
                      查看详情
                    </el-button>
                  </div>
                </el-card>
              </el-timeline-item>
            </el-timeline>

            <div v-if="hasMoreActivities" class="load-more">
              <el-button type="text" @click="loadMoreActivities" :loading="loadingMore">
                加载更多动态
              </el-button>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import {
  getUserFromLocalStorage,
  initializeUserInLocalStorage
} from '@/utils/localStorageUser'
import {
  EditPen,
  Share,
  Location,
  Calendar,
  ChatDotRound,
  User,
  Star,
  Refresh,
  Loading,
  Select
} from '@element-plus/icons-vue'

const router = useRouter()

// 用户信息
const userInfo = reactive({
  username: '用户名',
  avatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
  description: '这是一个个性签名，可以描述用户的兴趣爱好等',
  verified: true,
  vipLevel: 3,
  location: '北京',
  joinDate: '2023-01-15',
  email: '',
  phone: '',
  sex: 'secret',
  birthday: ''
})

// 用户统计数据
const userStats = reactive({
  dynamic: 123,
  following: 456,
  followers: 7890,
  likes: 12345,
  views: 67890,
  favorites: 234
})

// 动态数据
const activities = ref([
  {
    id: 1,
    type: 'like',
    content: '点赞了视频',
    target: 'Vue3 实战教程：从入门到精通',
    time: '2024-11-06T10:30:00Z'
  },
  {
    id: 2,
    type: 'comment',
    content: '评论了文章',
    target: 'Element Plus 组件库最佳实践',
    time: '2024-11-05T16:20:00Z'
  },
  {
    id: 3,
    type: 'post',
    content: '发布了新动态',
    target: '今天学习了一个新的前端框架',
    time: '2024-11-04T09:15:00Z'
  }
])

// UI状态
const loading = ref(false)
const loadingMore = ref(false)
const hasMoreActivities = ref(true)

// 处理方法
const handleEditProfile = () => {
  router.push('/user/settings')
}

const handleShareProfile = () => {
  ElMessage.success('分享功能开发中')
  // 实际项目中这里可以集成社交分享SDK
}

const handleAvatarClick = () => {
  // 头像点击事件，可以用于更换头像
  ElMessage.info('点击了头像')
}

const refreshActivities = async () => {
  loading.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    ElMessage.success('动态已刷新')
  } catch (error) {
    ElMessage.error('刷新失败')
  } finally {
    loading.value = false
  }
}

const loadMoreActivities = async () => {
  loadingMore.value = true
  try {
    // 模拟加载更多
    await new Promise(resolve => setTimeout(resolve, 800))
    // 这里应该是API调用添加新数据
    ElMessage.info('已加载更多动态')
  } catch (error) {
    ElMessage.error('加载失败')
  } finally {
    loadingMore.value = false
  }
}

const navigateTo = (page) => {
  const routes = {
    dynamic: '/dynamic',
    following: '/following',
    followers: '/followers',
    favorites: '/favorites',
    achievements: '/achievements',
    settings: '/settings'
  }
  router.push(routes[page] || '/')
}

const viewActivity = (activity) => {
  ElMessage.info(`查看动态: ${activity.target}`)
}

// 工具函数
const formatCount = (count) => {
  if (!count) return '0'
  if (count >= 100000000) {
    return (count / 100000000).toFixed(1) + '亿'
  }
  if (count >= 10000) {
    return (count / 10000).toFixed(1) + '万'
  }
  return count.toString()
}

const formatJoinDate = (dateString) => {
  if (!dateString) return '未知时间'
  try {
    const date = new Date(dateString)
    return `${date.getFullYear()}年${date.getMonth() + 1}月`
  } catch {
    return dateString
  }
}

const formatActivityTime = (timeString) => {
  if (!timeString) return ''
  try {
    const date = new Date(timeString)
    const now = new Date()
    const diff = now - date

    const minutes = Math.floor(diff / 60000)
    const hours = Math.floor(diff / 3600000)
    const days = Math.floor(diff / 86400000)

    if (minutes < 60) return `${minutes}分钟前`
    if (hours < 24) return `${hours}小时前`
    if (days < 7) return `${days}天前`

    return date.toLocaleDateString('zh-CN')
  } catch {
    return timeString
  }
}

const getActivityType = (type) => {
  const types = {
    like: 'primary',
    comment: 'success',
    post: 'warning',
    share: 'info'
  }
  return types[type] || 'primary'
}

// 生命周期
onMounted(() => {
  // 从 localStorage 加载用户数据
  loadUserFromLocalStorage()
  console.log('Profile page mounted')
})

// 从 localStorage 加载用户信息
const loadUserFromLocalStorage = () => {
  const userData = getUserFromLocalStorage()
  if (userData) {
    Object.assign(userInfo, userData)
  } else {
    // 如果没有用户数据，初始化默认数据
    const defaultUser = initializeUserInLocalStorage()
    Object.assign(userInfo, defaultUser)
  }
}
</script>

<style scoped>
.profile-page {
  min-height: 100vh;
  background: linear-gradient(180deg, #f5f7fa 0%, #ffffff 100%);
}

.user-header {
  position: relative;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 60px 20px 40px;
  color: white;
}

.header-background {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.3);
}

.user-info-card {
  position: relative;
  display: flex;
  align-items: center;
  gap: 24px;
  max-width: 1200px;
  margin: 0 auto;
}

.avatar-section {
  position: relative;
  flex-shrink: 0;
}

.user-avatar {
  border: 4px solid rgba(255, 255, 255, 0.3);
  cursor: pointer;
  transition: all 0.3s ease;
}

.user-avatar:hover {
  transform: scale(1.05);
  border-color: rgba(255, 255, 255, 0.6);
}

.avatar-fallback {
  font-size: 32px;
  font-weight: bold;
}

.verify-badge {
  position: absolute;
  bottom: 2px;
  right: 2px;
  width: 24px;
  height: 24px;
  background: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
}

.user-basic-info {
  flex: 1;
  min-width: 0;
}

.username-section {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 8px;
}

.username {
  margin: 0;
  font-size: 28px;
  font-weight: 600;
}

.vip-tag {
  font-size: 12px;
  padding: 4px 8px;
}

.user-signature {
  margin: 0 0 12px 0;
  font-size: 16px;
  opacity: 0.9;
  line-height: 1.4;
}

.user-meta {
  display: flex;
  gap: 20px;
  font-size: 14px;
  opacity: 0.8;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 4px;
}

.user-actions {
  flex-shrink: 0;
  display: flex;
  gap: 12px;
}

.main-content {
  max-width: 1200px;
  margin: -40px auto 0;
  padding: 0 20px 40px;
  position: relative;
}

.stats-section {
  margin-bottom: 30px;
}

.user-stats-card {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  height: fit-content;
}

.stats-title {
  margin: 0 0 20px 0;
  font-size: 18px;
  font-weight: 600;
  color: #18191c;
}

.stats-grid {
  display: grid;
  gap: 16px;
  margin-bottom: 20px;
}

.stat-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
}

.stat-item:hover {
  background: #e9ecef;
  transform: translateY(-2px);
}

.stat-value {
  font-size: 24px;
  font-weight: 700;
  color: #00a1d6;
}

.stat-label {
  font-size: 14px;
  color: #61666d;
}

.stat-icon {
  position: absolute;
  right: 16px;
  color: #adb5bd;
  font-size: 16px;
}

.extended-stats {
  border-top: 1px solid #f1f3f4;
  padding-top: 16px;
}

.extended-stat {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  font-size: 14px;
}

.extended-label {
  color: #61666d;
}

.extended-value {
  font-weight: 600;
  color: #18191c;
}

.recent-activity {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.activity-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.activity-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #18191c;
}

.loading-activities,
.empty-activities {
  padding: 40px 20px;
  text-align: center;
  color: #999;
}

.loading-icon {
  font-size: 32px;
  margin-bottom: 12px;
  animation: spin 1s linear infinite;
}

.activity-item {
  padding: 8px 0;
}

.activity-card {
  border: none;
  border-radius: 8px;
}

.activity-content {
  display: flex;
  align-items: flex-start;
  gap: 12px;
}

.activity-icon {
  flex-shrink: 0;
  width: 32px;
  height: 32px;
  background: #f0f2f5;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #00a1d6;
}

.activity-details {
  flex: 1;
}

.activity-text {
  margin: 0 0 4px 0;
  font-size: 14px;
  color: #18191c;
}

.activity-target {
  font-size: 13px;
  color: #61666d;
}

.activity-actions {
  margin-top: 8px;
}

.load-more {
  text-align: center;
  margin-top: 20px;
  padding-top: 16px;
  border-top: 1px solid #f0f0f0;
}

.quick-nav {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.quick-nav h3 {
  margin: 0 0 20px 0;
  font-size: 18px;
  font-weight: 600;
  color: #18191c;
}

.nav-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  gap: 16px;
}

.nav-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  text-align: center;
}

.nav-item:hover {
  background: #00a1d6;
  color: white;
  transform: translateY(-2px);
}

.nav-icon {
  font-size: 24px;
  margin-bottom: 8px;
}

.nav-item:hover .nav-icon {
  color: white;
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .user-info-card {
    flex-direction: column;
    text-align: center;
    gap: 16px;
  }

  .user-actions {
    width: 100%;
    justify-content: center;
  }

  .main-content {
    margin-top: -20px;
    padding: 0 12px 20px;
  }

  .stats-grid {
    grid-template-columns: 1fr;
  }

  .nav-grid {
    grid-template-columns: repeat(2, 1fr);
  }

  .user-meta {
    flex-direction: column;
    gap: 8px;
    align-items: center;
  }
}
</style>